<template>
    <div class="customer-container">
        <div class="header">
            <el-row :gutter="20">
                <el-col :span="24">
                    <div class="filter-container">
                        <el-card class="filter-card">
                            <el-row :gutter="20">
                                <el-col :span="16">
                                    <div class="filter-item">
                                        <el-button type="primary" @click="handleAdd" class="add-button">
                                            <el-icon><i-ep-plus /></el-icon>新增客户
                                        </el-button>
                                        <span class="label">客户名称：</span>
                                        <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable
                                            @keyup.enter="handleSearch" style="width: 35%" />
                                        <div class="inline-buttons">
                                            <el-button type="warning" @click="handleSearch">查询</el-button>
                                            <el-button @click="resetSearch">重置</el-button>
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-card>
                    </div>
                </el-col>
            </el-row>
        </div>

        <div class="content">
            <el-card>
                <el-table v-loading="loading" :data="tableData" style="width: 100%" border
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="45" />
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="customerCode" label="客户编号" min-width="120" align="center" />
                    <el-table-column prop="customerName" label="客户名称" min-width="150" show-overflow-tooltip />
                    <el-table-column prop="region" label="所在区域" min-width="120" align="center" />
                    <el-table-column prop="contactPerson" label="联系人" min-width="100" align="center" />
                    <el-table-column label="操作" width="150" align="center" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-container">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[15, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 新增客户对话框 -->
        <add-customer-dialog v-model:visible="addDialogVisible" @success="handleAddSuccess" />

        <!-- 编辑客户对话框 -->
        <add-customer-dialog v-model:visible="editDialogVisible" :is-edit="true" :customer-data="currentCustomer"
            @success="handleEditSuccess" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import axios from "axios"
import AddCustomerDialog from "../customer/AddCustomerDialog.vue"
import { Plus } from "@element-plus/icons-vue"
import provinceCityData from "province-city-china/data"
import { read } from '../../../stores/host'
// 直辖市列表
const directCities = ["北京市", "上海市", "天津市", "重庆市"]

// 省市数据
const provinceOptions = provinceCityData.province.map((province:any) => ({
    value: province.name,
    label: province.name,
    code: province.province,
}))

// 城市选项
const cityOptions:any = ref([])

const getCityOptions = (provinceCode: string) => {
    return provinceCityData.city
        .filter((city:any) => city.province === provinceCode)
        .map((city:any) => ({
            value: city.name,
            label: city.name,
        }))
}

// 搜索表单
const searchForm:any = reactive({
    customerName: "",
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows:any = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentCustomer:any = ref(null)

// 获取客户列表数据
const fetchData = async () => {
    loading.value = true
    try {
        const response = await read.get(
            "/saleread/api/Customer/GetCustomerList",
            {
                params: {
                    customerName: searchForm.customerName,
                    pageIndex: currentPage.value,
                    pageSize: pageSize.value,
                },
            }
        )

        if (response.data && response.data.code === 200) {
            tableData.value = response.data.data.pageData.map((item: any) => ({
                id: item.id,
                customerCode: item.customerCode,
                customerName: item.customerName,
                region: `${item.province || ""}${item.city ? "-" + item.city : ""}`,
                contactPerson: item.contactName,
                status: "已提交",
            }))

            total.value = response.data.data.totalCount || tableData.value.length
        } else {
            ElMessage.error(response.data?.msg || "获取客户列表失败")
            tableData.value = []
            total.value = 0
        }

        loading.value = false
    } catch (error) {
        console.error("获取客户列表失败:", error)
        ElMessage.error("获取客户列表失败")
        loading.value = false
        tableData.value = []
        total.value = 0
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

// 重置搜索
const resetSearch = () => {
    Object.keys(searchForm).forEach((key) => {
        searchForm[key] = ""
    })
    currentPage.value = 1
    fetchData()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchData()
}

// 页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchData()
}

// 表格选择变化
const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
}

// 新增客户
const handleAdd = () => {
    addDialogVisible.value = true
}

// 新增成功回调
const handleAddSuccess = () => {
    fetchData()
}

// 查看客户
const handleView = (row: any) => {
    ElMessage.info(`查看客户: ${row.customerName}`)
}

// 编辑客户
const handleEdit = async (row: any) => {
    currentCustomer.value = { ...row }
    if (row.region) {
        const [province, city] = row.region.split("-")
        currentCustomer.value.province = province
        currentCustomer.value.city = city || ""
        // 处理直辖市
        if (directCities.includes(province)) {
            cityOptions.value = [{ value: province, label: province }]
        } else {
            // 获取省份对应的城市列表
            const provinceData = provinceCityData.province.find((p:any) => p.name === province)
            if (provinceData) {
                cityOptions.value = provinceCityData.city
                    .filter((c:any) => c.province === provinceData.province)
                    .map((c:any) => ({
                        value: c.name,
                        label: c.name,
                    }))
            }
        }
    }
    editDialogVisible.value = true
}

// 编辑成功回调
const handleEditSuccess = () => {
    editDialogVisible.value = false
    fetchData()
}

// 删除客户
const handleDelete = (row: any) => {
    ElMessageBox.confirm(`确定要删除客户 ${row.customerName} 吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            try {
                const response = await read.delete(
                    `/salewrite/api/Customer/DeleteCustomer?id=${row.id}`
                )

                if (response.data && response.data.code === 200) {
                    ElMessage.success("删除成功")
                    fetchData()
                } else {
                    ElMessage.error(response.data?.msg || "删除客户失败")
                }
            } catch (error) {
                console.error("删除客户失败:", error)
                ElMessage.error("删除客户失败")
            }
        })
        .catch(() => {
            ElMessage.info("已取消删除")
        })
}

onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.customer-container {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.add-button {
    margin-right: 50px;
    width: 80px;
}

.label {
    margin-right: 15px;
}

.inline-buttons {
    display: inline-flex;
    margin-left: 10px;
    gap: 10px;
}

.text-right {
    text-align: right;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>
